<template>
  <el-dialog
    v-model="visible"
    :title="title"
    :width="width"
    :top="top"
    :modal="modal"
    :close-on-click-modal="closeOnClickModal"
    :close-on-press-escape="closeOnPressEscape"
    :before-close="handleBeforeClose"
    :destroy-on-close="destroyOnClose"
    :custom-class="customClass"
  >
    <!-- 表单内容 -->
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-position="labelPosition"
      :label-width="labelWidth"
      :size="formSize"
    >
      <slot name="form" :form-data="formData" :form-rules="formRules">
        <!-- 默认表单项 -->
        <el-form-item
          v-for="field in formFields"
          :key="field.prop"
          :label="field.label"
          :prop="field.prop"
          :required="field.required"
        >
          <!-- 输入框 -->
          <el-input
            v-if="field.type === 'input' || !field.type"
            v-model="formData[field.prop]"
            :type="field.inputType || 'text'"
            :placeholder="field.placeholder"
            :maxlength="field.maxlength"
            :disabled="field.disabled"
            :clearable="field.clearable !== false"
          />
          
          <!-- 数字输入框 -->
          <el-input-number
            v-else-if="field.type === 'number'"
            v-model="formData[field.prop]"
            :min="field.min"
            :max="field.max"
            :step="field.step"
            :precision="field.precision"
            :placeholder="field.placeholder"
            :disabled="field.disabled"
            style="width: 100%;"
          />
          
          <!-- 文本域 -->
          <el-input
            v-else-if="field.type === 'textarea'"
            v-model="formData[field.prop]"
            type="textarea"
            :rows="field.rows || 3"
            :placeholder="field.placeholder"
            :maxlength="field.maxlength"
            :disabled="field.disabled"
          />
          
          <!-- 选择器 -->
          <el-select
            v-else-if="field.type === 'select'"
            v-model="formData[field.prop]"
            :placeholder="field.placeholder"
            :disabled="field.disabled"
            :clearable="field.clearable !== false"
            :multiple="field.multiple"
            style="width: 100%;"
          >
            <el-option
              v-for="option in field.options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
              :disabled="option.disabled"
            />
          </el-select>
          
          <!-- 单选框组 -->
          <el-radio-group
            v-else-if="field.type === 'radio'"
            v-model="formData[field.prop]"
            :disabled="field.disabled"
          >
            <el-radio
              v-for="option in field.options"
              :key="option.value"
              :label="option.value"
              :disabled="option.disabled"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>
          
          <!-- 复选框组 -->
          <el-checkbox-group
            v-else-if="field.type === 'checkbox'"
            v-model="formData[field.prop]"
            :disabled="field.disabled"
          >
            <el-checkbox
              v-for="option in field.options"
              :key="option.value"
              :label="option.value"
              :disabled="option.disabled"
            >
              {{ option.label }}
            </el-checkbox>
          </el-checkbox-group>
          
          <!-- 开关 -->
          <el-switch
            v-else-if="field.type === 'switch'"
            v-model="formData[field.prop]"
            :disabled="field.disabled"
            :active-text="field.activeText"
            :inactive-text="field.inactiveText"
          />
          
          <!-- 日期选择器 -->
          <el-date-picker
            v-else-if="field.type === 'date'"
            v-model="formData[field.prop]"
            :type="field.dateType || 'date'"
            :placeholder="field.placeholder"
            :disabled="field.disabled"
            :clearable="field.clearable !== false"
            style="width: 100%;"
          />
          
          <!-- 时间选择器 -->
          <el-time-picker
            v-else-if="field.type === 'time'"
            v-model="formData[field.prop]"
            :placeholder="field.placeholder"
            :disabled="field.disabled"
            :clearable="field.clearable !== false"
            style="width: 100%;"
          />
          
          <!-- 自定义插槽 -->
          <slot
            v-else-if="field.type === 'slot'"
            :name="field.prop"
            :field="field"
            :form-data="formData"
          />
        </el-form-item>
      </slot>
    </el-form>

    <!-- 额外内容插槽 -->
    <slot name="extra" :form-data="formData" />

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <slot name="footer" :form-data="formData" :loading="loading">
          <el-button @click="handleCancel" :disabled="loading">
            {{ cancelText }}
          </el-button>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleConfirm"
          >
            {{ confirmText }}
          </el-button>
        </slot>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { createFieldRules } from '@/utils/formValidationRules';

export default {
  name: 'FormDialog',
  
  props: {
    // 对话框显示状态
    modelValue: {
      type: Boolean,
      default: false
    },
    
    // 对话框标题
    title: {
      type: String,
      default: '表单对话框'
    },
    
    // 对话框宽度
    width: {
      type: [String, Number],
      default: '600px'
    },
    
    // 距离顶部距离
    top: {
      type: String,
      default: '15vh'
    },
    
    // 是否显示遮罩层
    modal: {
      type: Boolean,
      default: true
    },
    
    // 是否可以通过点击遮罩层关闭
    closeOnClickModal: {
      type: Boolean,
      default: false
    },
    
    // 是否可以通过ESC关闭
    closeOnPressEscape: {
      type: Boolean,
      default: true
    },
    
    // 关闭时销毁子元素
    destroyOnClose: {
      type: Boolean,
      default: false
    },
    
    // 自定义类名
    customClass: {
      type: String,
      default: ''
    },
    
    // 表单数据
    formData: {
      type: Object,
      required: true
    },
    
    // 表单字段配置
    formFields: {
      type: Array,
      default: () => []
    },
    
    // 表单验证规则
    formRules: {
      type: Object,
      default: () => ({})
    },
    
    // 表单标签位置
    labelPosition: {
      type: String,
      default: 'right'
    },
    
    // 表单标签宽度
    labelWidth: {
      type: String,
      default: '100px'
    },
    
    // 表单尺寸
    formSize: {
      type: String,
      default: 'default'
    },
    
    // 确认按钮文本
    confirmText: {
      type: String,
      default: '确定'
    },
    
    // 取消按钮文本
    cancelText: {
      type: String,
      default: '取消'
    },
    
    // 加载状态
    loading: {
      type: Boolean,
      default: false
    },
    
    // 自动生成验证规则
    autoValidation: {
      type: Boolean,
      default: true
    }
  },
  
  emits: ['update:modelValue', 'confirm', 'cancel', 'close'],
  
  computed: {
    visible: {
      get() {
        return this.modelValue;
      },
      set(value) {
        this.$emit('update:modelValue', value);
      }
    },
    
    /**
     * 合并后的表单验证规则
     */
    mergedFormRules() {
      if (!this.autoValidation) {
        return this.formRules;
      }
      
      const autoRules = {};
      this.formFields.forEach(field => {
        if (field.validation) {
          if (typeof field.validation === 'string') {
            autoRules[field.prop] = createFieldRules(field.validation, {
              required: field.required,
              label: field.label
            });
          } else if (Array.isArray(field.validation)) {
            autoRules[field.prop] = field.validation;
          }
        }
      });
      
      return { ...autoRules, ...this.formRules };
    }
  },
  
  methods: {
    /**
     * 处理关闭前事件
     */
    handleBeforeClose(done) {
      this.$emit('close');
      done();
    },
    
    /**
     * 处理确认
     */
    async handleConfirm() {
      try {
        // 表单验证
        await this.$refs.formRef.validate();
        
        // 触发确认事件
        this.$emit('confirm', { ...this.formData });
      } catch (error) {
        console.warn('表单验证失败:', error);
      }
    },
    
    /**
     * 处理取消
     */
    handleCancel() {
      this.$emit('cancel');
      this.visible = false;
    },
    
    /**
     * 验证表单
     * @returns {Promise<boolean>}
     */
    async validate() {
      try {
        await this.$refs.formRef.validate();
        return true;
      } catch (error) {
        return false;
      }
    },
    
    /**
     * 验证指定字段
     * @param {string} prop - 字段名
     * @returns {Promise<boolean>}
     */
    async validateField(prop) {
      try {
        await this.$refs.formRef.validateField(prop);
        return true;
      } catch (error) {
        return false;
      }
    },
    
    /**
     * 清除验证
     * @param {string|Array} props - 字段名或字段名数组
     */
    clearValidation(props) {
      this.$refs.formRef.clearValidate(props);
    },
    
    /**
     * 重置表单
     */
    resetFields() {
      this.$refs.formRef.resetFields();
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

.dialog-footer .el-button:first-child {
  margin-left: 0;
}

/* 表单样式优化 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-form-item__content) {
  line-height: 32px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 0 5%;
  }
  
  :deep(.el-form--label-right .el-form-item__label) {
    text-align: left;
    float: none;
    display: block;
    width: auto !important;
    padding: 0 0 10px 0;
  }
  
  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}
</style>